package com.bank.abmock.config;

import com.alibaba.fastjson.JSONObject;
import com.bank.abmock.Utils.JsonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mifmif.common.regex.Generex;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JsonRouteConfig extends RouteConfig{
    /*
     * 请求报文规则，由ConfigLoad解析文件得
     * */
    Map<String, Object> requestRules;
    /*
     * 返回报文规则，由ConfigLoad解析文件得
     * */
    Map<String, Object> responseRules;

    @Override
    public Object process(Object request) {
        Map<String, Object> resContent = (Map<String, Object>) request;
        Map<String, Object> rspContent = new HashMap<>();
        //校验请求报文
        for(String key : requestRules.keySet()){
            String rule = (String)requestRules.get(key);
            if("int".equals(rule)){
                Object val = resContent.get(key);
                //判断int类型
                if(val instanceof Integer){
                    System.out.println("key:"+key + "val:" + val + "不符合" + "rule:" + rule);
                }
            }
        }
        //生成返回报文
//        for(String key : responseRules.keySet()){
//            String rule = (String)responseRules.get(key);
//            if(rule.startsWith("regex")){
//                String regex = org.apache.commons.lang3.StringUtils.substringAfter(rule,"regex");
//                Generex generex = new Generex(regex);
//                String randomStr = generex.random();
//                resContent.put(key, randomStr);
//            }
//
//            if(StringUtils.startsWithIgnoreCase(rule, "${")){
//                //解析${}中的键
//                resContent.put(key, resContent.get(key));
//            }
//
//        }

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JSONObject json = new JSONObject(responseRules);
            JsonNode root = objectMapper.readTree(json.toJSONString());
            String respStr = JsonUtils.generateValues(root).toString();
            return respStr;
        } catch (IOException e) {
            e.printStackTrace();
            return "解析json失败";
        }
    }

    public Map<String, Object> getRequestRules() {
        return requestRules;
    }

    public void setRequestRules(Map<String, Object> requestRules) {
        this.requestRules = requestRules;
    }

    public Map<String, Object> getResponseRules() {
        return responseRules;
    }

    public void setResponseRules(Map<String, Object> responseRules) {
        this.responseRules = responseRules;
    }
}
